package org.cliff.message.platform.demo.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.cliff.message.platform.core.annotation.MessageConsumer;
import org.cliff.message.platform.core.domain.MPRequestHeaderConstants;
import org.cliff.message.platform.core.domain.WorkerNode;
import org.cliff.message.platform.core.mapper.WorkerNodeMapper;
import org.cliff.message.platform.demo.dto.User;
import org.cliff.message.platform.demo.service.DemoService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

/**
 * @author 刘文
 * @date 2023/10/9
 */
@RestController
@RequestMapping("/demo")
public class DemoController {

    @Autowired
    private WorkerNodeMapper workerNodeMapper;

    @Autowired
    private DemoService demoService;

    @MessageConsumer()
    @GetMapping("/igeList")
    public List<WorkerNode> list() {
        return workerNodeMapper.selectList(new QueryWrapper<>());
    }

    @MessageConsumer
    @PostMapping("/short")
    public User shortResponse(@RequestBody User user){
        user.setName("ChangedToShort");
        return user;
    }

    @MessageConsumer
    @PostMapping("/clone-user")
    public List<User> clone(@RequestBody User user) {
        List<User> users = new ArrayList<>(user.getUserCount());
        for (int i = 0; i < user.getUserCount(); i++) {
            User copy = new User();
            BeanUtils.copyProperties(user, copy);
            copy.setName("User" + i);
            users.add(user);
        }
        return users;
    }


    @MessageConsumer
    @GetMapping("/error")
    public String error() {
        return demoService.error();
    }

    @MessageConsumer
    @GetMapping("/error-retry")
    public String errorRetry() {
        return demoService.error();
    }

    @MessageConsumer
    @PostMapping("/user-success")
    public List<WorkerNode> list(@RequestBody User user) {
        System.out.println(user);
        return workerNodeMapper.selectList(new QueryWrapper<>());
    }

    @MessageConsumer
    @PostMapping("/user-retry-n-times")
    public List<WorkerNode> retryNTimes(@RequestBody User user, HttpServletRequest request) {
        String retryTime = request.getHeader(MPRequestHeaderConstants.AUTO_RETRY_COUNT);
        int retryCount = retryTime == null ? 0 : Integer.parseInt(retryTime);
        int expectedRetryTime = user.getRetryTime() == null ? 0: user.getRetryTime();
        if (retryCount < expectedRetryTime) {
            throw new IllegalStateException("Need retry");
        }
        return workerNodeMapper.selectList(new QueryWrapper<>());
    }
}
